package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class CategoryController {
    //查询所有菜品
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/category/findAll")
    public ResultInfo findAll() {
        List<Category> list = null;
        //先查询缓存
        String categoryKey = "category_list";
        //判断是否有缓存
        if (redisTemplate.hasKey(categoryKey)) {
             //有数据 查询缓存
            list = (List<Category>) redisTemplate.opsForValue().get(categoryKey);
            log.info("查询redis缓存");
        }else{
            // no redis没有数据
            // 调用service查询MySQL
            list = categoryService.findAll();
            log.info("查询MySQL数据库");
            //把数据库存查到的数据传给redis
            redisTemplate.opsForValue().set(categoryKey,list);
        }


        return ResultInfo.success(list);
    }
     //新增
    @PostMapping("/category")
    public ResultInfo categoryAdd(@RequestBody Category category) {
        ResultInfo resultInfo = categoryService.categoryAdd(category);

        redisTemplate.delete("category_list");
        return resultInfo;

    }
         //修改
    @PutMapping("/category")
    public ResultInfo categoryUpdata(@RequestBody Category category) {
        categoryService.categorUpdat(category);
        redisTemplate.delete("category_list");
        return ResultInfo.success();
    }
     //删除
    @DeleteMapping("/category")
    public ResultInfo categoryDele(Long id) {
        ResultInfo resultInfo = categoryService.categoryDeletByid(id);
        redisTemplate.delete("category_list");
        return resultInfo;
    }


}


